package com.vhall.component.plugin.core.service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.vhall.component.entity.account.dto.WatchUserInfoDTO;
import com.vhall.component.entity.account.vo.WatchLoginSsoVO;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.properties.ThirdPartyProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * SsoService- sso第三方调用服务
 *ThirdPartyService
 * @author xing.wang
 * @date 2023/8/2
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SsoService {
    @Value("${spring.profiles.active:''}")
    private String active;
    private final ThirdPartyProperties thirdPartyProperties;
    private final GuoXinService guoXinService;
    /**
     * 使用 code 获取用户三方信息
     * @param code sso校验code
     * @return 获取用户信息
     */
    public JSONObject getThirdUserInfo(String code){
        String authCheckCodeUrl = thirdPartyProperties.getSso().getAuthCheckCodeUrl();
        String urlString = authCheckCodeUrl + "?code=" + code;
        HttpRequest httpRequest = HttpRequest.get(urlString);
        HttpResponse execute = null;
        String body ;
        try{
            execute = httpRequest.execute();
            body = execute.body();
        }catch (Exception e){
            log.error("通过调用三方发生错误{},请求体:{},响应体:{}","sso登录", httpRequest.toString(), execute, e);
            throw new BusinessException(BizErrorCode.BIZ_THIRD_FAILED);
        }
        JSONObject data = JSONObject.parseObject(body);
        if (!"0".equals(data.getString("code"))) {
            log.error("通过 三方 获取管理后台用户信息发生错误,返回结果不符合预期,请求体:{},响应体:{}", httpRequest.toString(),execute);
            throw new BusinessException(BizErrorCode.BIZ_THIRD_FAILED);
        }
        JSONObject userData = data.getJSONObject("data");
        if (Objects.isNull(userData)) {
            log.error("通过 三方 获取管理后台用户信息发生错误,返回结果不符合预期,请求体:{},响应体:{}", httpRequest.toString(),execute);
            throw  new BusinessException(BizErrorCode.BIZ_THIRD_INFO_ERR);
        }else{
            log.info("当前登录用户信息为:{}",userData.toJSONString());
        }
        return userData;
    }

    /**
     * 观众端国信提供的获取用户信息
     * @param vo
     * @return
     */
    public WatchUserInfoDTO getThirdUserInfoWatch(WatchLoginSsoVO vo){
        JSONObject thirdUserInfoWatch = guoXinService.getThirdUserInfoWatch(vo);
        WatchUserInfoDTO dto = new WatchUserInfoDTO();
        String usercode = thirdUserInfoWatch.getString("usercode");
        String custid = thirdUserInfoWatch.getString("custid");
        String fundid = thirdUserInfoWatch.getString("fundid");
        String mobile = thirdUserInfoWatch.getString("mobile");
        String name = thirdUserInfoWatch.getString("name");
        String staff = thirdUserInfoWatch.getString("isStaff");
        String orgcode = thirdUserInfoWatch.getString("orgcode");
        String islogin = thirdUserInfoWatch.getString("islogin");
        String openid = thirdUserInfoWatch.getString("openid");
        if (StrUtil.isBlank(mobile)) {
            String mobile1 = generatePhoneNumber(usercode);
            dto.setMobile(mobile1);
        }else{
            if (NumberUtil.isNumber(mobile)) {
                dto.setMobile(mobile);
            }else{
                String mobile1 = generatePhoneNumber(mobile);
                dto.setMobile(mobile1);
            }
        }
        dto.setCustId(custid);
        dto.setUserCode(usercode);
        dto.setFundId(fundid);
        dto.setStaff(Objects.equals(staff,"1")?1:0);
        dto.setOrgCode(orgcode);
        dto.setIslogin(islogin);
        if (Objects.equals(active,"test")) {
            if (StrUtil.isBlank(openid)) {
                openid = "test";
            }
            dto.setOpenid(openid);
        }else{
            dto.setOpenid(openid);
        }
        if (StrUtil.isBlank(name)) {
            dto.setName("name"+RandomUtil.randomNumbers(6));
        }else{
            dto.setName(name);
        }
        return dto;
    }

    /**
     * 根据传入值生成一个手机号
     * @param mobile
     * @return
     */
    public static String generatePhoneNumber(String mobile) {
        String digits = "";
        if(StrUtil.isNotBlank(mobile)) {
            int hashCode = mobile.hashCode();
            if(hashCode < 0) {
                hashCode = Math.abs(hashCode);
            }
            digits = hashCode + "";
        }else{
            return generatePhoneNumber(RandomUtil.randomString(5));
        }
        String numStr = String.format("%09d", Integer.parseInt(digits)).substring(0,8);
        return "930" + numStr;
    }

}
